import { useIntervalFn } from "@vueuse/core";
import { ref, onUnmounted } from "vue";

export default function useCountDown() {
  // 计时器数值
  let count = ref(0);

  // 创建计时器
  const { pause, isActive, resume } = useIntervalFn(
    () => {
      if (count.value <= 0) {
        // 停止计时器
        pause();
      } else {
        count.value--;
      }
    },
    1000,
    { immediate: false }
  );

  // 开始计时器
  const start = (value) => {
    if (!isActive.value) {
      count.value = value;
      // 开始计时器
      resume();
    }
  };

  onUnmounted(pause);

  return {
    count,
    start,
  };
}
